
package org.ambientbi.webapp.rest.resources;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response.Status;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

import org.ambientbi.webapp.rest.objects.SavedReport;
import org.ambientbi.webapp.service.DummyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;


@Component
@Path("/saiku/{username}/repository")
@Scope("request")
@XmlAccessorType(XmlAccessType.NONE)
public class BasicRepositoryResource {

    private static final Logger log = LoggerFactory.getLogger(BasicRepositoryResource.class);
    
    private String path;
    
    private URL repoURL;

	private DummyService dummyService;

    public void setPath(String path) throws URISyntaxException {
		repoURL = this.getClass().getClassLoader().getResource(path);
		this.path = (new File(repoURL.toURI())).getAbsolutePath();
	}
    

	@Autowired
	public void setDummyService(DummyService ds) {
		dummyService = ds;
	}

	
	/**
	 * Get Saved Reports.
	 * @return A list of SavedQuery Objects.
	 */
    @GET
    @Produces({"application/json" })
     public List<SavedReport> getSavedReports() {
    	List<SavedReport> queries = new ArrayList<SavedReport>();
    	try {
    		      if (repoURL != null) {
    		    	  if ( repoURL.getProtocol().equals("file")) {
    		    		  File[] files = new File(repoURL.toURI()).listFiles();
    		    		  for (File file : files) {
    		    			  if (!file.isHidden()) {
    		    				  SimpleDateFormat sf = new SimpleDateFormat("dd - MMM - yyyy HH:mm:ss");
    		    				  String filename = file.getName();
    		    				  if (filename.endsWith(".prpt")) {
    		    					  filename = filename.substring(0,filename.length() - ".prpt".length());
    		    					  SavedReport sq = new SavedReport(filename, sf.format(new Date(file.lastModified())));
    		    					  queries.add(sq);
    		    				  }
    		    			  }
    		    		  }
    		    	  }
    		      }
    		      else {
    		    	  throw new Exception("repo URL is null");
    		      }
		} catch (Exception e) {
			log.error(this.getClass().getName(),e);
		}
		return queries;
    }
    
    /**
     * Delete Query.
     * @param queryName - The name of the query.
     * @return A GONE Status if the query was deleted, otherwise it will return a NOT FOUND Status code.
     */
	@DELETE
    @Produces({"application/json" })
	@Path("/{queryname}")
	public Status deleteReport(@PathParam("queryname") String queryName){
		try{
			String uri = repoURL.toURI().toString();
			if (uri != null) {
				if (!queryName.endsWith(".prpt")) {
					queryName += ".prpt";
				}

				URL url = new URL(uri + queryName);
				File queryFile = null;
				try {
					queryFile = new File(url.toURI());
				} catch(URISyntaxException e) {
					queryFile = new File(url.getPath());
				}

				if (queryFile.delete()) {
					return(Status.GONE);
				}
			}
			throw new Exception("Cannot delete query file uri:" + uri);
		}
		catch(Exception e){
			log.error("Cannot delete query (" + queryName + ")",e);
			return(Status.NOT_FOUND);
		}
	}
	
	DELETE
    @Produces({"application/json" })
	@Path("/dummy")
	public String dummyCall() {
		return dummyService.dummyTest();
		
	}
	/**
	 * Load a query.
	 * @param queryName - The name of the query to load.
	 * @return A Saiku Query Object.
	 */
//	@GET
//    @Produces({"application/xml" })
//	@Path("/{queryname}")
//	public String loadReport(@PathParam("queryname") String queryName){
//		try{
//			String uri = repoURL.toURI().toString();
//			String filename = queryName;
//			if (uri != null) {
//				if (!filename.endsWith(".prpt")) {
//					filename += ".prpt";
//				}
//				URL url = new URL(uri + filename);
//				File queryFile = null;
//				try {
//					queryFile = new File(url.toURI());
//				} catch(URISyntaxException e) {
//					queryFile = new File(url.getPath());
//				}
//				if (queryFile.exists()) {
//					FileReader fi = new FileReader(queryFile);
//					BufferedReader br = new BufferedReader(fi);
//					String chunk ="",xml ="";
//					while ((chunk = br.readLine()) != null) {
//						xml += chunk + "\n";
//					}
//					return xml;
//				}
//				else {
//					throw new Exception("File does not exist:" + uri);
//				}
//			}
//			else {
//				throw new Exception("Cannot save query because uriis null");
//			}
//		} catch(Exception e){
//			log.error("Cannot load query (" + queryName + ")",e);
//		}
//		return null;
//	}
}
